<template>
	<div style="border: 1px solid #ccc">
		<Toolbar style="border-bottom: 1px solid #ccc" :editor="editor" :default-config="toolbarConfig" :mode="mode" />
		<Editor v-model="html" style="height: 400px; overflow-y: hidden" :default-config="editorConfig" :mode="mode" @onCreated="onCreated" />
	</div>
</template>

<script>
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css'
export default {
	name: 'Weditor',
	components: { Editor, Toolbar },
	props: {
		id: {
			type: String,
			default: 'e'
		},

		data: {
			type: String,
			default: ''
		},
		desc: {
			type: String,
			default: ''
		},
		isClear: {
			type: Boolean,
			default: false
		},
		height: {
			type: Number,
			default: 200
		},
		disabled: {
			type: Boolean,
			default: false
		}
	},
	data() {
		return {
			editor: null,
			html: '',
			toolbarConfig: {},
			editorConfig: {
				placeholder: '请输入内容...',
				MENU_CONF: {
					uploadImage: {
						// server: constant.uploadUrl,
						fieldName: 'file',
						// 自定义插入图片
						customInsert(res, insertFn) {
							// res 即服务端的返回结果
							// 从 res 中找到 url alt href ，然后插图图片
							let url = `${globalUrl.url}${res.data.realPath}`
							insertFn(url, res.data.filename, '')
						},
						// 小于该值就插入 base64 格式（而不上传），默认为 0
						base64LimitSize: 10 * 1024 * 1024 // 10mb
					}
				}
			},
			mode: 'default' // or 'simple'
		}
	},
	watch: {
		data() {
			console.log(44, this.data)
			const editor = this.editor // 获取 editor 实例
			if (editor == null) {
				return
			}
			this.editor.setHtml(this.data)
		}
	},
	mounted() {},
	beforeUnmount() {
		const editor = this.editor
		if (editor == null) {
			return
		}
		editor.destroy() // 组件销毁时，及时销毁编辑器
	},
	methods: {
		onCreated(editor) {
			this.editor = Object.seal(editor) // 一定要用 Object.seal() ，否则会报错
			this.editor.setHtml(this.data)

			this.editor.on('change', evt => {
				this.$emit('change', {
					item: this.item,
					data: this.editor.getHtml()
				})
			})
		}
	}
}
</script>
